<?php


namespace app\shop\service\user;


use app\shop\common\consts\Consts;
use app\shop\model\order\OrderModel;
use app\shop\model\user\FriendModel;
use app\shop\model\user\MessageModel;
use app\shop\model\user\UserModel;
use app\shop\service\BaseService;

class FriendService extends BaseService
{

    public static function getInstance()
    {
        return new FriendModel();
    }

    public function __construct()
    {
    }

    /**
     * 好友ID
     * @param UserModel $userInfo
     * @return array
     * @throws \Exception
     */
    public static function getFriendIds(UserModel $userInfo): array
    {
        try {
            $userId = $userInfo['user_id'];
            $roleId = $userInfo['role_id'];

            $idArr = [];
            // 设计
            if ($roleId == Consts::DESIGN_ID) {
                $arr0 = array_column(self::getAllServiceLeaderList(), 'user_id');
                $arr1 = array_column(self::getAllSaleLeaderList(), 'user_id');
                $arr2 = array_column(self::getUserDepartmentFriendList($userId, [Consts::CUSTOMER_ID]), 'user_id');
                $idArr = array_merge($arr0, $arr1, $arr2);
            }
            // 设计经理
            if ($roleId == Consts::DESIGN_LEADER_ID) {
                $arr0 = array_column(self::getAllServiceLeaderList(), 'user_id');
                $arr1 = array_column(self::getAllSaleLeaderList(), 'user_id');
                $arr2 = array_column(self::getUserDepartmentFriendList($userId, [Consts::CUSTOMER_ID]), 'user_id');
                $idArr = array_merge($arr0, $arr1, $arr2);
            }
            // 客户
            if ($roleId == Consts::CUSTOMER_ID) {
                $arr0 = array_column(self::getAllSaleLeaderList(), 'user_id');
                $arr1 = array_column(self::getAllServiceLeaderList(), 'user_id');
                $arr2 = array_column(self::getUserDepartmentFriendList($userId, [Consts::SALE_ID]), 'user_id');
                $arr3 = array_column(self::getUserDepartmentFriendList($userId, [Consts::DESIGN_LEADER_ID, Consts::DESIGN_ID]), 'user_id');
                $idArr = array_merge($arr0, $arr1, $arr2, $arr3);
            }
            // 售后总监
            if ($roleId == Consts::SERVICE_LEADER_ID) {
                $arr0 = array_column(self::getAllSaleLeaderList(), 'user_id');
                $arr1 = array_column(self::getAllServiceLeaderList($userId, 1), 'user_id');
                $arr2 = array_column(self::getAllDesignLeaderList(), 'user_id');
                $arr3 = array_column(self::getAllConsumerList(), 'user_id');
                $idArr = array_merge($arr0, $arr1, $arr2, $arr3);
            }
            // 销售总监
            if ($roleId == Consts::SALE_LEADER_ID) {
                $arr0 = array_column(self::getAllSaleLeaderList($userId, 1), 'user_id');
                $arr1 = array_column(self::getAllServiceLeaderList(), 'user_id');
                $arr2 = array_column(self::getAllSaleList(), 'user_id');
                $arr3 = array_column(self::getAllConsumerList(), 'user_id');
                $idArr = array_merge($arr0, $arr1, $arr2, $arr3);
            }
            // 销售
            if ($roleId == Consts::SALE_ID) {
                $arr0 = array_column(self::getAllSaleLeaderList(), 'user_id');
                $arr1 = array_column(self::getSaleFriendList($userId), 'user_id');
                $idArr = array_merge($arr0, $arr1);
            }

            return $idArr;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage() . $exception->getLine());
        }
    }

    /**
     * 获取好友列表
     * @param UserModel $userInfo
     * @return array
     * @throws \Exception
     */
    public static function getDepartmentFriendList(UserModel $userInfo): array
    {
        try {
            $userId = $userInfo['user_id'];
            $roleId = $userInfo['role_id'];
            $arr = [
                'sale_leader' => 0,
                'sale_leader_list' => [],
                'service_leader' => 0,
                'service_leader_list' => [],
                'sale' => 0,
                'sale_list' => [],
                'designer' => 0,
                'designer_list' => [],
                'customer' => 0,
                'customer_list' => [],
            ];
            // 设计师
            if ($roleId == Consts::DESIGN_ID) {
                $list = self::getUserDepartmentFriendList($userId, [Consts::CUSTOMER_ID]);
                $arr['customer'] = count($list);
                $arr['customer_list'] = $list;
            }
            // 设计经理
            if ($roleId == Consts::DESIGN_LEADER_ID) {
                $list = self::getUserDepartmentFriendList($userId, [Consts::CUSTOMER_ID]);
                $arr['customer'] = count($list);
                $arr['customer_list'] = $list;
            }
            // 用户
            if ($roleId == Consts::CUSTOMER_ID) {
                $list = self::getAllSaleLeaderList();
                $arr['sale_leader'] = count($list);
                $arr['sale_leader_list'] = $list;

                $list1 = self::getAllServiceLeaderList();
                $arr['service_leader'] = count($list1);
                $arr['service_leader_list'] = $list1;

                $list2 = self::getUserDepartmentFriendList($userId, [Consts::SALE_ID]);
                $arr['sale'] = count($list2);
                $arr['sale_list'] = $list2;

                $list3 = self::getUserDepartmentFriendList($userId, [Consts::DESIGN_ID, Consts::DESIGN_LEADER_ID]);
                $arr['designer'] = count($list3);
                $arr['designer_list'] = $list3;
            }
            // 售后总监
            if ($roleId == Consts::SERVICE_LEADER_ID) {
                $list = self::getAllSaleLeaderList();
                $arr['sale_leader'] = count($list);
                $arr['sale_leader_list'] = $list;

                $list1 = self::getAllServiceLeaderList($userId, 1);
                $arr['service_leader'] = count($list1);
                $arr['service_leader_list'] = $list1;

                $list2 = self::getAllDesignLeaderList();
                $arr['designer'] = count($list2);
                $arr['designer_list'] = $list2;

                $list3 = self::getAllConsumerList();
                $arr['customer'] = count($list3);
                $arr['customer_list'] = $list3;
            }
            // 销售总监
            if ($roleId == Consts::SALE_LEADER_ID) {
                $list = self::getAllSaleLeaderList($userId, 1);
                $arr['sale_leader'] = count($list);
                $arr['sale_leader_list'] = $list;

                $list2 = self::getAllServiceLeaderList();
                $arr['service_leader'] = count($list2);
                $arr['service_leader_list'] = $list2;

                $list3 = self::getAllSaleList();
                $arr['sale'] = count($list3);
                $arr['sale_list'] = $list3;

                $list4 = self::getAllConsumerList();
                $arr['customer'] = count($list4);
                $arr['customer_list'] = $list4;
            }
            // 销售
            if ($roleId == Consts::SALE_ID) {
                $list = self::getAllSaleLeaderList();
                $arr['sale_leader'] = count($list);
                $arr['sale_leader_list'] = $list;

                $list2 = self::getUserDepartmentFriendList($userId, [Consts::CUSTOMER_ID]);
                $arr['customer'] = count($list2);
                $arr['customer_list'] = $list2;
            }
            return $arr;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 获取用户某个角色好友列表
     * @param int $userId
     * @param array $roleId
     * @return array
     * @throws \Exception
     */
    public static function getUserDepartmentFriendList(int $userId, array $roleId): array
    {
        try {
            $where[] = ['create_user', '=', $userId];
            $where[] = ['status', '=', 1];
            $idArr = self::getInstance()
                ->where($where)
                ->column('friend_user_id');
            if (!$idArr) {
                return [];
            }
            $list = UserModel::with(['department', 'role'])
                ->field('user_id,realname,avatar,department_id,role_id')
                ->whereIn('user_id', $idArr)
                ->whereIn('role_id', $roleId)
                ->select()
                ->toArray();
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 获取某个人的好友列表
     * @param int $userId
     * @return array
     * @throws \Exception
     */
    public static function getSaleFriendList(int $userId): array
    {
        try {
            $where[] = ['create_user', '=', $userId];
            $where[] = ['status', '=', 1];
            $idArr = self::getInstance()
                ->where($where)
                ->column('friend_user_id');
            if (!$idArr) {
                return [];
            }
            $list = UserModel::with(['department', 'role'])
                ->field('user_id,realname,avatar,department_id,role_id')
                ->whereIn('user_id', $idArr)
                ->select()
                ->toArray();
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 获取所有售后总监
     * @param int $selfUid
     * @param int $isInclude
     * @return array
     * @throws \Exception
     */
    public static function getAllServiceLeaderList(int $selfUid = 0, int $isInclude = 0): array
    {
        try {
            $where = [];
            $where[] = ['role_id', '=', Consts::SERVICE_LEADER_ID];
            $where[] = ['status', '=', 1];
            if ($isInclude) {
                $where[] = ['user_id', '<>', $selfUid];
            }
            $list = UserModel::where($where)
                ->with(['department', 'role'])
                ->field('user_id,realname,avatar,department_id,role_id')
                ->select()
                ->toArray();
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }


    /**
     * 获取所有销售总监
     * @param int $selfUid
     * @param int $isInclude
     * @return array
     * @throws \Exception
     */
    public static function getAllSaleLeaderList(int $selfUid = 0, int $isInclude = 0): array
    {
        try {
            $where = [];
            $where[] = ['role_id', '=', Consts::SALE_LEADER_ID];
            $where[] = ['status', '=', 1];
            if ($isInclude) {
                $where[] = ['user_id', '<>', $selfUid];
            }
            $list = UserModel::where($where)
                ->with(['department', 'role'])
                ->field('user_id,realname,avatar,department_id,role_id')
                ->select()
                ->toArray();
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 获取所有销售
     * @return array
     * @throws \Exception
     */
    public static function getAllSaleList()
    {
        try {
            $list = UserModel::with(['department', 'role'])
                ->field('user_id,realname,avatar,department_id,role_id')
                ->where('role_id', Consts::SALE_ID)
                ->where('status', 1)
                ->select()
                ->toArray();
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 获取所有设计经理
     * @return array
     * @throws \Exception
     */
    public static function getAllDesignLeaderList()
    {
        try {
            $list = UserModel::with(['department', 'role'])
                ->field('user_id,realname,avatar,department_id,role_id')
                ->whereIn('role_id', [Consts::DESIGN_LEADER_ID, Consts::DESIGN_ID])
                ->where('status', 1)
                ->select()
                ->toArray();
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 获取所有客户
     * @return array
     * @throws \Exception
     */
    public static function getAllConsumerList()
    {
        try {
            $list = UserModel::where('status', 1)
                ->with(['department', 'role'])
                ->field('user_id,realname,avatar,department_id,role_id')
                ->where('role_id', Consts::CUSTOMER_ID)
                ->select()
                ->toArray();
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 删除好友
     * @param $userId
     * @param $friendId
     * @return bool
     * @throws \Exception
     */
    public static function removeFriend($userId, $friendId)
    {
        try {
            return true;
            if (!$userId || !$friendId) {
                return true;
            }
            $info = self::getInstance()
                ->where('friend_user_id', $friendId)
                ->where('create_user', $userId)
                ->where('status', 1)
                ->find();
            if (!$info) {
                return true;
            }
            $info->status = 0;
            $info->save();
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 添加好友
     * @param $userId
     * @param $friendId
     * @return bool
     * @throws \Exception
     */
    public static function addFriend($userId, $friendId)
    {
        try {
            return true;
            if (!$userId || !$friendId) {
                return true;
            }
            $info = self::getInstance()
                ->where('friend_user_id', $friendId)
                ->where('create_user', $userId)
                ->find();
            if (!$info) {
                self::getInstance()::create([
                    'friend_user_id' => $friendId,
                    'is_invite' => 1,
                    'create_user' => $userId,
                ]);
                return true;
            }
            if ($info['status'] == 1) {
                return true;
            }
            $info->status = 1;
            $info->save();
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 创建订单添加好友
     * @param $userId
     * @return bool
     * @throws \Exception
     */
    public static function createOrderFriend($userId)
    {
        try {
            $userArr = UserModel::whereIn('role_id', [Consts::SALE_LEADER_ID, Consts::SERVICE_LEADER_ID])
                ->where('status', 1)
                ->column('user_id');
            foreach ($userArr as $uid) {
                self::addFriend($uid, $userId);
                self::addFriend($userId, $uid);
            }
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
}